<template>
    <transition appear name="slide">
        <music-list
            :title="title"
            :bg-image="bgImage"
            :songs="songs"
            :isLoadError="isLoadError"
            @loadRefresh="refreshDate"
        >
        </music-list>
    </transition>
</template>

<script type="text/ecmascript-6">
    import MusicList from 'components/music-list/music-list'

    import { mapGetters } from 'vuex'
    import { getSingerDetail } from 'api/singer'
    import { ERR_OK } from 'api/config'
    import { createSong, isValidMusic, processSongsUrl } from 'common/js/classes/song'

    export default {
        name: 'singer-detail',
        data() {
            return {
                songs: [],
                isLoadError: false
            }
        },
        computed: {
            title() {
                return this.singer.name
            },
            bgImage() {
                return this.singer.avatar
            },
            // vux获取数据的语法糖
            ...mapGetters([
                'singer'
            ])
        },
        methods: {
            _getDetail() {
                if (!this.singer.id) {
                    // 回退到歌手列表
                    this.$router.push('/singer')
                    return
                }
                getSingerDetail(this.singer.id).then((res) => {
                    if (res.code === ERR_OK) {
                        processSongsUrl(this._normalizeSongs(res.data.list)).then((songs) => {
                            this.songs = songs
                        }).catch((err) => {
                            console.log(err)
                            this.isLoadError = true
                        })
                    }
                })
            },
            _normalizeSongs(list) {
                let ret = []
                list.forEach((item) => {
                    let { musicData } = item
                    if (isValidMusic(musicData)) {
                        ret.push(createSong(musicData))
                    }
                })
                return ret
            },
            refreshDate() {
                this.isLoadError = false
                this._getDetail()
            }
        },
        created() {
            this._getDetail(this.singer.id)
        },
        components: {
            MusicList
        }
    }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
    @import "~common/stylus/variable"
    .slide-enter-active, .slide-leave-active
        transition: all .3s
    .slide-enter, .slide-leave-to
        transform: translate3d(100%, 0, 0)
</style>